package com.tian.config;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author tianwc  公众号：java后端技术全栈、面试专栏
 * @version 1.0.0
 * @date 2023年05月16日 22:53
 * 博客地址：<a href="http://woaijava.cc/">博客地址</a>
 */
@Component
public class DistributedLock {

    @Resource
    private RedissonClient redissonClient;


    public void lock(String key) {
        RLock rLock = redissonClient.getLock(key);
        rLock.lock();
    }
    public void lock(String lockKey, TimeUnit unit, int leaseTime) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock(leaseTime, unit);
    }
    public boolean tryLock(String key) {
        RLock lock = redissonClient.getLock(key);
        return lock.tryLock();
    }


    public void unlock(String key) {
        RLock lock = redissonClient.getLock(key);
        if (lock != null && lock.isHeldByCurrentThread()) {
            lock.unlock();
        }
    }
}
